/***************************************************************************
 *   Copyright (C) 2008-2009 by Dominik Kapusta       <d@ayoy.net>         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License as        *
 *   published by the Free Software Foundation; either version 2.1 of      *
 *   the License, or (at your option) any later version.                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this program; if not, write to                     *
 *   the Free Software Foundation, Inc.,                                   *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

#include "avatarmanager.h"
#include "imageprocessor.h"

// Qt includes
#include <QNetworkRequest>
#include <QNetworkReply>


namespace ImageDownload {

AvatarManager* AvatarManager::m_instance = 0;

AvatarManager* AvatarManager::instance(QObject *parent)
{
    if (!m_instance) {
        m_instance = new AvatarManager(parent);
    }
    return m_instance;
}

AvatarManager::AvatarManager(QObject *parent) :
    QObject( parent )
{
    m_imageCache.setMaxCost(1000);
    m_baseUrl = QUrl("http://avatar.me.zdn.vn");
}

AvatarManager::~AvatarManager()
{
    m_instance = 0;
}

void AvatarManager::imageGet(const QString &imageUrl)
{
    if (m_imageCache.contains(imageUrl)) {
        //emit imageReady();
        emit imageReadyForUrl(imageUrl);
        return;
    }

    QUrl url(imageUrl);
    QString host(url.host());
    QNetworkRequest request(url);

    if ( !m_connections.contains(host)) {
        m_connections.insert(host, new QNetworkAccessManager(this));
        connect(m_connections[host], SIGNAL(finished(QNetworkReply*)),
                this, SLOT(requestFinished(QNetworkReply*)));
    }

    m_connections[host]->get(request);
    m_imageCache.insert(imageUrl, new QPixmap);
}

bool AvatarManager::contains(const QString &imageUrl) const
{
    return m_imageCache.contains(imageUrl);
}

QPixmap* AvatarManager::imageFromUrl(const QString &imageUrl) const
{
    return m_imageCache[imageUrl];
}

void AvatarManager::requestFinished(QNetworkReply *reply)
{
    /*
     * Reply is finished!
     * We'll ask for the reply about the Redirection attribute
     * http://doc.trolltech.com/qnetworkrequest.html#Attribute-enum
     */

    QVariant possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    // We'll deduct if the redirection is valid in the redirectUrl function
    m_urlRedirectedTo = this->redirectUrl(possibleRedirectUrl.toUrl(), m_urlRedirectedTo);

    // If the URL is not empty, we're being redirected.
    if (!m_urlRedirectedTo.isEmpty()) {

        m_urlRedirectedTo = m_baseUrl.resolved(m_urlRedirectedTo);

        // Insert to redirect Map
        insertRedirectUrlMap(reply->url().toString(), m_urlRedirectedTo.toString());

        /* We'll do another request to the redirection url. */
        QUrl url(m_urlRedirectedTo);
        QString host(url.host());

        if ( !m_connections.contains(host)) {
            m_connections.insert(host, new QNetworkAccessManager(this));
            connect(m_connections[host], SIGNAL(finished(QNetworkReply*)),
                    this, SLOT(requestFinished(QNetworkReply*)));
        }

        m_connections[host]->get(QNetworkRequest(m_urlRedirectedTo));

    } else {
        // Get data
        int replyCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        if (replyCode != 200)
            return;

        QPixmap *pixmap = new QPixmap;
        pixmap->loadFromData(reply->readAll());

        m_originalUrlString = getOriginalUrl(reply->url().toString());
        m_imageCache.insert(m_originalUrlString, pixmap);

        //emit imageReady();
        emit imageReadyForUrl(m_originalUrlString);

        /* ...so this can be cleared. */
        m_urlRedirectedTo.clear();
    }
    /* Clean up. */
    reply->deleteLater();
}

QUrl AvatarManager::redirectUrl(const QUrl& possibleRedirectUrl,
                                const QUrl& oldRedirectUrl) const
{
    QUrl redirectUrl;
    /*
     * Check if the URL is empty and
     * that we aren't being fooled into a infinite redirect loop.
     * We could also keep track of how many redirects we have been to
     * and set a limit to it, but we'll leave that to you.
     */
    if(!possibleRedirectUrl.isEmpty() &&
            possibleRedirectUrl != oldRedirectUrl) {
        redirectUrl = possibleRedirectUrl;
    }
    return redirectUrl;
}

QNetworkAccessManager* AvatarManager::createNetworkAccessManager()
{
    QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this);

    // We'll handle the finished reply in replyFinished
    connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));
    return networkAccessManager;
}

void AvatarManager::insertRedirectUrlMap(const QString &oldUrl, const QString &newUrl)
{
    if (m_redirectUrlMap.size() == 0)
        m_redirectUrlMap.insert(oldUrl, newUrl);

    QMap<QString, QString>::ConstIterator it;
    for (it = m_redirectUrlMap.begin(); it != m_redirectUrlMap.end(); it++) {
        if (it.value() == oldUrl) {
            m_redirectUrlMap[it.key()] = newUrl;
            return;
        }
    }

    m_redirectUrlMap.insert(oldUrl, newUrl);
}

QString AvatarManager::getOriginalUrl(const QString &url)
{
    if (m_redirectUrlMap.size() == 0)
        return url;

    QMap<QString, QString>::ConstIterator it;
    for (it = m_redirectUrlMap.begin(); it != m_redirectUrlMap.end(); it++) {
        if (it.value() == url)
            return it.key();
    }

    return url;
}

/*! \class ImageDownload
    \brief A class for downlading images for Statuses.

    This is a class that provides interface for downloading user profile images
    for Statuses.
*/

/*! \fn ImageDownload::ImageDownload()
    A default constructor.
*/

/*! \fn void ImageDownload::imageGet( Entry *entry )
    This method invokes HttpConnection::prepareRequest() for a path
    given in \a entry, assigns allocated data to newly created
    ImageData instance and then issues QHttp::get().
    \param entry Entry for which the image will be downloaded.
*/

/*! \fn void ImageDownload::clearData()
    Forces clearing of temporary images store, gathered while updating timeline.
*/

/*! \fn void ImageDownload::imageReadyForUrl( const QString& path, QPixmap image )
    Emitted when the request is finished and the image is ready to be displayed.
    \param path The image's URL.
    \param image The downloaded image.
*/

} // namespace ImageDownload
